﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Configuration; /* 读写配置文件app.config */
using Comm;/* 使用配置文件的自定义类 */
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFFileTransfer;

namespace WCFHost
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConfigSet.CreateConfig();
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "请选择保存路径";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = folder.SelectedPath;
                // 写入配置文件
                ConfigSet.SetValue("SavePath", folder.SelectedPath);
            }
        }

        private ServiceHost host = null;
        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "Stop Service") // 关闭服务
            {
                CloseService();
                button2.Text = "Start Service";
                return;
            }

            // 开启WCF服务
            host = new ServiceHost(typeof(WCFFileTransfer.FileTransfer));

            // 绑定
            System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();
            
            // 终结点
            host.AddServiceEndpoint(typeof(WCFFileTransfer.IFileTransfer), httpBinding, "http://localhost:8002/");

            if (host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null)
            {
                // 行为
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;

                // 元数据地址
                behavior.HttpGetUrl = new Uri("http://localhost:8002/FileTransfer");
                host.Description.Behaviors.Add(behavior);

                host.Opened += delegate { button2.Text = "Stop Service"; };
                //启动
                host.Open();
            }
        }

        // 关闭服务
        private void CloseService()
        {
            if (host != null)
                host.Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseService();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = ConfigSet.GetValue("SavePath"); // 显示默认的路径
        }

    }
}
